﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Gui.CompletionWindow;
using ICSharpCode.TextEditor.Document;
using ICSharpCode.TextEditor.Actions;

namespace Bing.Studio
{
    public partial class FrmQueryBuilder : BaseForm
    {
        private static int _index = 1;

        private string _strConnectionString;
        private string _strTableName;
        private FileInfo _fiSql;

        public FrmQueryBuilder()
        {
            InitializeComponent();
        }

        public FrmQueryBuilder(string strConnectionString, string strTableName)
        {
            _strConnectionString = strConnectionString;
            _strTableName = strTableName;

            InitializeComponent();
        }

        public FrmQueryBuilder(string strConnectionString, string strTableName, FileInfo fiSql)
        {
            _strConnectionString = strConnectionString;
            _strTableName = strTableName;
            _fiSql = fiSql;

            InitializeComponent();
        } 

        /****************************************************************************************************/

        #region /*自定义方法*/

        public void ExecuteSql()
        {
            var db = new SQLServerDataStructuresHelper(_strConnectionString);
            try
            {
                var result = db.Execute(textEditorControl1.Text);
                this.dataGridView1.DataSource = result;
                this.textBox1.Text = String.Format("{0}行受影响", result.Rows.Count);
            }
            catch(Exception ex)
            {
                SendNotification(ex);
            }
        }

        #endregion

        /****************************************************************************************************/

        private void FrmQueryBuilder_Load(object sender, EventArgs e)
        {
            this.textEditorControl1.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("TSQL");
            this.textEditorControl1.Encoding = Encoding.Default;

            if (_fiSql == null)
            {
                this.TabText = String.Format("SQLQuery_{0}.sql", _index++);
                this.textEditorControl1.Text = "SELECT * FROM " + _strTableName;
            }
            else
            {
                this.TabText = _fiSql.Name;
                this.textEditorControl1.Text = File.ReadAllText(_fiSql.FullName);
            }

            ExecuteSql();
        }

        /****************************************************************************************************/
    }
}
